<template>
	<div>
		<template>
			<!-- table表格 -->
			<div>
				<template>
					<!-- 搜索条件 -->
					<div class="params">
						<el-form
							ref="ruleForm"
							:model="queryData"
							:rules="rules"
							label-width="100px"
							:inline="true"
						>
							<div>
								<el-form-item
									label="任务标题:"
									prop="depositTitle"
								>
									<el-input
										v-model="queryData.depositTitle"
										size="mini"
										placeholder="请输入"
										clearable
										:disabled="!editVisibleChlLid"
										style="width: 180px"
										maxlength="6"
									></el-input>
								</el-form-item>
								<el-form-item
									label="任务开关:"
									label-width="110px"
									prop="depositSwitch"
								>
									<el-switch
										v-model="queryData.depositSwitch"
										:disabled="!editVisibleChlLid"
										active-text="开"
										inactive-text="关"
									></el-switch>
								</el-form-item>
								<el-form-item
									label="任务有效期:"
									prop="depositValidity"
								>
									<el-input
										v-model="queryData.depositValidity"
										size="mini"
										placeholder="请输入"
										clearable
										:disabled="!editVisibleChlLid"
										style="width: 180px"
									>
										<span slot="append">天</span>
									</el-input>
								</el-form-item>
								<el-form-item
									label="被邀请人累计充值要求:"
									label-width="170"
									prop="depositInviteesAmount"
								>
									<el-input
										v-model="
											queryData.depositInviteesAmount
										"
										size="mini"
										placeholder="请输入"
										clearable
										:disabled="!editVisibleChlLid"
										style="width: 180px"
										@input="
											onFilter(
												queryData.depositInviteesAmount
											)
										"
									>
										<span slot="append">元</span>
									</el-input>
								</el-form-item>
								<el-form-item
									label="红利方式:"
									label-width="110px"
									prop="depositRewardType"
								>
									<el-select
										v-model="queryData.depositRewardType"
										size="mini"
										placeholder="请选择"
										:disabled="!editVisibleChlLid"
										style="width: 180px"
									>
										<el-option
											v-for="item in paymentMethodObj"
											:key="item.id"
											:label="item.label"
											:value="item.id"
										></el-option>
									</el-select>
								</el-form-item>
							</div>
							<div>
								<el-form-item
									label="同IP限制:"
									prop="depositIpRule"
								>
									<el-select
										v-model="queryData.depositIpRule"
										size="mini"
										placeholder="请选择"
										:disabled="!editVisibleChlLid"
										collapse-tags
										style="width: 175px"
									>
										<el-option
											label="是"
											:value="1"
										></el-option>
										<el-option
											label="否"
											:value="0"
										></el-option>
									</el-select>
								</el-form-item>
								<el-form-item
									label="同设备限制:"
									prop="depositDeviceRule"
								>
									<el-select
										v-model="queryData.depositDeviceRule"
										size="mini"
										placeholder="请选择"
										:disabled="!editVisibleChlLid"
										collapse-tags
										style="width: 175px"
									>
										<el-option
											label="是"
											:value="1"
										></el-option>
										<el-option
											label="否"
											:value="0"
										></el-option>
									</el-select>
								</el-form-item>
							</div>
						</el-form>
					</div>
				</template>
			</div>
			<!-- 添加按钮 -->
			<div style="margin-top:10px">
				<div class="btn-add" @click="handleAdd">
					<span>添加</span>
				</div>
			</div>
			<el-form
				ref="tableForm"
				class="tabs-content-table"
				:model="queryData1.tableForm"
			>
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="queryData1.tableForm.inviteDepositRuleList"
					style="width: 100%"
					:header-cell-style="getRowClass"
					:span-method="arraySpanMethod"
					:row-style="{ height: '30px' }"
					:cell-style="{ padding: '0px' }"
				>
					<el-table-column
						type="index"
						align="center"
						label="序号"
						width="50"
					></el-table-column>
					<el-table-column
						align="center"
						label="转入场馆金额（元）"
						width="210"
					>
						<template slot-scope="scope">
							<el-form-item
								class="form-item"
								:prop="
									`inviteDepositRuleList.${
										scope.$index
									}.depositVenueAmount`
								"
								:rules="[
									{
										required: true,
										validator: getVaLiDate(
											'depositVenueAmount',
											'转入场馆金额（元）',
											scope.$index,
											'inviteDepositRuleList'
										),
										trigger: ['change', 'blur']
									}
								]"
							>
								<el-input
									v-model.trim="scope.row.depositVenueAmount"
									size="mini"
									label=""
									:maxlength="9"
									:disabled="!editVisibleChlLid"
									:controls="false"
									style="width:80%"
								></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column
						v-if="queryData.depositRewardType === 1"
						align="center"
						label="赠送金额（元）"
						width="180"
					>
						<template slot-scope="scope">
							<el-form-item
								:prop="
									`inviteDepositRuleList.${
										scope.$index
									}.validAmount`
								"
								:rules="[
									{
										required: true,
										validator: getVaLiDate(
											'validAmount',
											'赠送金额（元）',
											scope.$index,
											'inviteDepositRuleList'
										),
										trigger: ['change', 'blur']
									}
								]"
							>
								<el-input
									v-model.trim="scope.row.validAmount"
									size="mini"
									label=""
									:maxlength="9"
									:disabled="!editVisibleChlLid"
									:controls="false"
									style="width:80%"
								></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column
						v-if="queryData.depositRewardType === 2"
						align="center"
						label="赠送比例 (%)"
						width="180"
					>
						<template slot-scope="scope">
							<el-form-item
								:prop="
									`inviteDepositRuleList.${
										scope.$index
									}.validAmount`
								"
								:rules="[
									{
										required: true,
										validator: getVaLiDate(
											'validAmount',
											'赠送比例 (%)',
											scope.$index,
											'inviteDepositRuleList'
										),
										trigger: ['change', 'blur']
									}
								]"
							>
								<el-input
									v-model.trim="scope.row.validAmount"
									size="mini"
									label=""
									:maxlength="9"
									:disabled="!editVisibleChlLid"
									:controls="false"
									style="width:80%"
								></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column
						v-if="queryData.depositRewardType === 2"
						align="center"
						label="赠送上限（元）"
						width="180"
					>
						<template slot-scope="scope">
							<el-form-item
								:prop="
									`inviteDepositRuleList.${
										scope.$index
									}.validTopLimit`
								"
								:rules="[
									{
										required: true,
										validator: getVaLiDate(
											'validTopLimit',
											'赠送上限（元）',
											scope.$index,
											'inviteDepositRuleList'
										),
										trigger: ['change', 'blur']
									}
								]"
							>
								<el-input
									v-model.trim="scope.row.validTopLimit"
									size="mini"
									label=""
									:maxlength="9"
									:disabled="!editVisibleChlLid"
									:controls="false"
									style="width:80%"
								></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="流水要求（倍）"
						width="180"
					>
						<template slot-scope="scope">
							<el-form-item
								:prop="
									`inviteDepositRuleList.${
										scope.$index
									}.validMultiple`
								"
								:rules="[
									{
										required: true,
										validator: getVaLiDate12(
											'validMultiple',
											'流水要求（倍）',
											scope.$index,
											'inviteDepositRuleList'
										),
										trigger: ['change', 'blur']
									}
								]"
							>
								<el-input
									v-model.trim="scope.row.validMultiple"
									size="mini"
									label=""
									:maxlength="9"
									:disabled="!editVisibleChlLid"
									:controls="false"
									style="width:80%"
								></el-input>
							</el-form-item>
						</template>
					</el-table-column>

					<el-table-column
						prop="operating"
						align="center"
						label="操作"
						width="120"
					>
						<template slot-scope="scope">
							<el-button
								type="danger"
								icon="el-icon-delete"
								size="medium"
								:disabled="
									!editVisibleChlLid || scope.$index === 0
								"
								@click="handleDelete(scope.$index)"
							>
								删除
							</el-button>
							<div style="height:18px"></div>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
		</template>
	</div>
</template>

<script>
import list from '@/mixins/list'

export default {
	mixins: [list],
	props: {
		editVisible: {
			type: Boolean,
			default: () => false
		}
	},
	data() {
		return {
			isTableErr: false,
			editVisibleChlLid: false,
			activeObj: [
				{ label: '首存时间开始计算', id: 1 },
				{ label: '注册时间开始计算', id: 2 }
			],
			paymentMethodObj: [
				{ label: '固定金额', id: 1 },
				{ label: '比例金额', id: 2 }
			],
			queryData: {
				depositTitle: '',
				TaskForm: '',
				RebateRatio: '',
				depositRewardType: 1,
				depositValidity: '',
				depositIpRule: 0,
				depositDeviceRule: 0,
				depositInviteesAmount: '',
				AwardConditions: 1,
				BonusMethod: '',
				depositMethod: '',
				depositSwitch: undefined
			},
			queryData1: {
				tableForm: {
					inviteDepositRuleList: [
						{
							depositVenueAmount: '',
							validAmount: '',
							validTopLimit: '',
							validMultiple: ''
						}
					]
				}
			}
		}
	},
	computed: {
		rules() {
			const reg1 = /^(([0-9]+))$/
			const validateBetRewardDay = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入'))
				} else if (!reg1.test(value) && value) {
					callback(new Error(`请输入正整数!`))
				} else if (value && +value === 0) {
					// setTimeout(() => {
					callback(new Error(`不能为0!`))
					// }, 1500)
				} else {
					callback()
				}
			}
			return {
				activeSwitch: [
					{ required: true, message: '', trigger: 'blur' }
				],
				activeName: [
					{
						required: true,
						message: '请输入活动名称',
						trigger: 'blur'
					}
				],
				activeTitle: [
					{
						required: true,
						message: '请输入活动主题',
						trigger: 'blur'
					}
				],
				activeObject: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				radio: [{ required: true, message: '请输入', trigger: 'blur' }],
				showTime: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				activeTime: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				ip: [{ required: true, message: '请输入', trigger: 'blur' }],
				equipment: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				inviteRadio: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				intervalTime: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				depositRewardType: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				depositIpRule: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				depositDeviceRule: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				depositInviteesAmount: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				depositValidity: [
					{
						required: true,
						validator: validateBetRewardDay,
						trigger: ['blur', 'change']
					}
				],
				RebateRatio: [
					{ required: true, message: '请输入', trigger: 'blur' }
				],
				depositTitle: [
					{ required: true, message: '请输入', trigger: 'blur' }
				]
			}
		}
	},
	watch: {
		'queryData.depositRewardType': {
			handler(val) {
				if (val) {
					this.$nextTick(() => {
						this.queryData1.tableForm.inviteDepositRuleList = []
						if (val && val === 1) {
							this.queryData1.tableForm.inviteDepositRuleList = [
								{
									depositVenueAmount: '',
									validAmount: '',
									validTopLimit: '',
									validMultiple: ''
								}
							]
						} else {
							this.queryData1.tableForm.inviteDepositRuleList = [
								{
									depositVenueAmount: '',
									validAmount: '',
									validMultiple: ''
								}
							]
						}
						// setTimeout(() => {
						// 	this.validate()
						// }, 500)
					})
				}
			},
			deep: true,
			immediate: true
		},
		// 规则配置的圆点检测
		queryData: {
			handler(el) {
				Object.keys(el).forEach((item) => {
					this.$nextTick(() => {
						this.$emit('appropriation')
					})
				})
			},
			deep: true
			// immediate: true
		},
		'queryData1.tableForm.inviteDepositRuleList': {
			handler(err) {
				if (err) {
					this.$emit('appropriation')
				}
			},
			deep: true
			// immediate: true
		},
		editVisible: {
			handler(val) {
				this.$nextTick(() => {
					this.editVisibleChlLid = val
				})
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		getSpan(list) {
			const newArr = []
			const obj = {}
			if (list.length > 1) {
				for (let i = 0; i < list?.length; i++) {
					if (i === 0) {
						obj.row = 1
						obj.col = 1
						newArr.push(obj)
					} else {
						if (list[i].id === list[i - 1].id) {
							newArr.push({ row: 0, col: 0 })
							newArr[0].row++
						} else {
							newArr.push({ row: 1, col: 1 })
						}
					}
				}
			}
			return newArr
		},

		arraySpanMethod({ column, rowIndex, columnIndex }) {
			if (this.queryData1.tableForm.inviteDepositRuleList.length <= 1) {
				return
			}

			const arr = this.getSpan(
				this.queryData1.tableForm.inviteDepositRuleList
			)

			const row = arr[rowIndex].row
			const col = arr[rowIndex].col
			if (column.label === '流水（倍）') {
				this.queryData1.tableForm.inviteDepositRuleList
				return {
					rowspan: row,
					colspan: col
				}
			}
		},

		// 随时校验
		validate() {
			this.$refs['tableForm'].validate((valid) => {
				if (valid) {
					return valid
				}
			})
		},
		// 删除单行
		handleDelete(index) {
			if (this.queryData1.tableForm.inviteDepositRuleList.length > 1) {
				this.queryData1.tableForm.inviteDepositRuleList.splice(index, 1)
			} else {
				return this.$message({
					message: '至少要保留一个配置行',
					type: 'warning'
				})
			}
		},
		// 添加
		handleAdd() {
			if (!this.editVisibleChlLid) return
			const template = {
				depositVenueAmount: undefined,
				validAmount: undefined,
				validMultiple: undefined
			}
			this.queryData1.tableForm.inviteDepositRuleList.push(template)

			this.$nextTick(() => {
				setTimeout(() => {
					this.validate()
					this.$emit('appropriation')
				}, 500)
			})
		},
		onFilter(val) {
			if (val) {
				val = val.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
				val = val.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
				val = val
					.replace('.', '$#$')
					.replace(/\./g, '')
					.replace('$#$', '.')
				val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') // 只能输入两个小数
				if (
					val.indexOf('.') < 0 &&
					val !== '' &&
					val.indexOf('0') === 0 &&
					val.length > 1
				) {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					val = val.replace('0', '')
				}
				this.queryData.depositInviteesAmount = val
			}
		},
		// cell 校验
		getVaLiDate(field, fieldName, index, typeName, submit = false) {
			return (rule, value, callback) => {
				const reg = /^(([0-9]+)|([0-9]+\.[0-9]{0,2}))$/
				this.$nextTick(() => {
					if (!value) {
						callback(new Error(`请输入${fieldName}!`))
						this.isTableErr = true
					} else if (!reg.test(value) && value) {
						callback(new Error(`请输入两位小数的正数!`))
						this.isTableErr = true
					} else if (value && +value === 0) {
						// setTimeout(() => {
						callback(new Error(`不能为0!`))
						// }, 1500)
					} else {
						callback()
					}
				})
			}
		},
		getVaLiDate12(field, fieldName, index, typeName, submit = false) {
			return (rule, value, callback) => {
				const reg = /^(([0-9]+))$/
				this.$nextTick(() => {
					if (!value) {
						callback(new Error(`请输入${fieldName}!`))
						this.isTableErr = true
					} else if (!reg.test(value) && value) {
						callback(new Error(`请输入正整数!`))
						this.isTableErr = true
					} else if (value && +value === 0) {
						// setTimeout(() => {
						callback(new Error(`不能为0!`))
						// }, 1500)
					} else {
						callback()
					}
				})
			}
		},

		// 删除table cell
		deleteRow() {}
	}
}
</script>

<style lang="scss" scoped>
.btn-add {
	width: 60px;
	height: 25px;
	line-height: 25px;
	span {
		display: flex;
		justify-content: center;
		background: #00a7f0;
		align-items: center;
		color: #ffff;
		font-size: 14px;
		cursor: pointer;
	}
}
.form-item ::v-deep .el-form-item__content {
	height: 30px;
	line-height: 30px;
}
::v-deep .el-table__row .el-form-item {
	margin-bottom: 15px;
}
//input-number 位置
::v-deep .el-form-item__content .el-input-group {
	vertical-align: baseline;
}
</style>
